<?php
/**
 * 登录控制器
 */
namespace Admin\Controller;
use Think\Controller;

class LoginController extends Controller {
    //后台登录页面
    public function index(){
        //如果已经登录，直接跳到后台主页
        $admin_id = \admin_helper::get_admin_id();
        if($admin_id){
            $this->redirect('index/index');
        }else{
            $this->display('index');
        }

    }

    //ajax检验管理员登录是否正确
    public function check(){
        if(!IS_AJAX){
            $data = array(
                'code'=> 201,
                'msg' => '非法访问方式'
            );
            $this->ajaxReturn($data);
        }
        $admin_name  = I('admin_name', '', 'trim');
        $password   = I('password', '', 'trim');

        $filter = array();
        //判断用户名是否为空
        if(!$admin_name){
            $data = array(
                'code'=> 202,
                'msg' => '登录账号不能为空'
            );
            $this->ajaxReturn($data);
        }else{
            $filter['admin_name'] = $admin_name;
        }
        //判断密码是否为空
        if(!$password){
            $data = array(
                'code'=> 202,
                'msg' => '登录密码不能为空'
            );
            $this->ajaxReturn($data);
        }else{
            $filter['password'] = password_encrypt($password);
        }

        $admin_info = _uri('admin', $filter);

        if($admin_info){
            //将admin_id存入session
            session('admin_id',$admin_info['id']);

            //获取登录来源，1：pc 2:手机 3：微信
            if(on_weixin()){
                $login_source = 3;
            }elseif(on_mobile()){
                $login_source = 2;
            }else{
                $login_source = 1;
            }
            //将登录信息存入登录日志
            M('login_history')->add(array(
                'admin_id'   => $admin_info['id'],
                'login_time' => date('Y-m-d H:i:s'),
                'login_ip'   => get_client_ip(),
                'login_source' => $login_source
            ));

            $data = array(
                'code' => 200,
                'msg' => '登录成功'
            );
            $this->ajaxReturn($data);
        }else{
            $data = array(
                'code' => 202,
                'msg' => '登录失败，请检查登录名和密码是否正确'
            );
            $this->ajaxReturn($data);

        }

    }

}